CONTENTS | INDEX | PREV | NEXT
strdup
NAME
strdup - duplicate a string using malloc
SYNOPSIS
char *s2 = strdup(s1);
const char *s1;
FUNCTION
strdup malloc's enough space to hold s1 including the terminating
nul and then copies s1 into this space, returning a pointer to
the new string. NULL is returned if space could not be allocated
due to low memory conditions.
free() may be used to free the returned string. The amount
malloc'd is (strlen(s1) + 1).
NOTE
strdup() is a non-standard function and may not exist in other
C enviroments.
EXAMPLE
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* Modifying string constants (quoted strings) may not be entirely
* portable. Normally one does not use strdup() to accomplish the
* following function but instead declares a char array statically
* initialized with the string, such as:
*
* char FuBar[] = { "This is a test" };
*
* Which can be modified in a portable fashion without having to
* duplicate the string.
*/
main()
{
char *s1 = "this is a test";
char *s2;
s2 = strdup(s1);
s2[0] = 'x';
puts(s2); /* xhis is a test */
free(s2);
s2 = strdup(s1);
s2[1] = '0';
puts(s2); /* t0is is a test */
free(s2);
return(0);
}
INPUTS
char *s1; pointer to the string to duplicate
RESULTS
char *s2; pointer to malloc'd space containing a duplicate
of the string s1 or NULL if space could not be
malloc'd.
SEE ALSO
malloc, free, strcpy, strlen